package com.feinno.urcs.group.interop.service;

import com.feinno.database.DataRow;
import com.feinno.database.DataTable;
import com.feinno.database.Database;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.fxdb.FXPoolService;
import com.feinno.urcs.group.fxdb.PooledDatabaseLoader;
import com.feinno.urcs.group.interop.FxDataValidateUserInfoDao;
import com.feinno.urcs.group.interop.entity.DataValidateGroupBaseInfo;
import com.feinno.urcs.group.interop.entity.DataValidateGroupMemberInfo;
import com.feinno.urcs.group.interop.entity.DataValidateUserMobileInfo;
import com.google.gson.Gson;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;
import org.helium.framework.annotations.ServiceSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@ServiceImplementation
public class FxDataValidateUserInfoDaoImpl implements FxDataValidateUserInfoDao {
	private static final Logger LOGGER = LoggerFactory.getLogger(FxDataValidateUserInfoDaoImpl.class);

	@FieldSetter(value = "${GRPDB_POOLS_XML}", loader = PooledDatabaseLoader.class)
	private Map<Integer, Database> grpdbs;
	@FieldSetter(value = "${UPDB_POOLS_XML}", loader = PooledDatabaseLoader.class)
	private Map<Integer, Database> updbs;
	@ServiceSetter
	private FXPoolService poolService;


	/**
	 * 获取指定PhysicalPool的GRPDB
	 *
	 * @return 返回Database连接
	 * @throws SQLException
	 */
	private Database getGrpDatabase(int logicalPool) throws Exception {

		int poolid = poolService.getPhyicalPool(logicalPool);
		return grpdbs.get(poolid);

	}

	private Database getUpDatabase(int logicalPool) throws Exception {

		int poolid = poolService.getPhyicalPool(logicalPool);
		return updbs.get(poolid);

	}

	public void getUserInfo(DataValidateGroupMemberInfo info) throws SQLException {
		String sb = "select UserId,MobileNo,LogicalPool from UP_User where UserId = " + info.getUserId();
		DataValidateUserMobileInfo result = null;
		try {
			DataTable dt = getUpDatabase(info.getLogicPool()).executeTable(sb);


			if (dt != null && dt.getRows().size() > 0) {

				DataRow resultSet = dt.getRow(0);
				long mobileNo = 0;
				try {
					mobileNo = resultSet.getLong("MobileNo");
					if (mobileNo != 0) {
						info.setMobileNo(String.valueOf(mobileNo));
					} else {
						throw new RuntimeException(String.format("userid=%s logicalPool=%s mobileNo is 0", info.getUserId(), info.getLogicPool()));
					}
				} catch (Exception ee) {
					LOGGER.info(String.format(" new UserMobileInfo error, DataValidateUserMobileInfo=%s ", info));
				}
			}
		} catch (Exception e) {
			LOGGER.error("DataValidateUserMobileInfo= " + new Gson().toJson(info), e);
		}
	}

//	public Map<Integer, DataValidateUserMobileInfo> getUserInfo(List<Integer> userIds) throws SQLException {
//		StringBuilder sb = new StringBuilder("select UserId,MobileNo,LogicalPool from UP_User where ");
//		for (int i = 0; i < userIds.size(); i++) {
//			sb.append(" UserId = ").append(userIds.get(i));
//			if (i < userIds.size() - 1) {
//				sb.append(" or ");
//			}
//		}
//		Connection connection = null;
//		PreparedStatement statement = null;
//		Map<Integer, DataValidateUserMobileInfo> result = new HashMap<Integer, DataValidateUserMobileInfo>();
//		try {
//			connection = updb.getConnection();
//			statement = connection.prepareStatement(sb.toString());
//			ResultSet resultSet = statement.executeQuery();
//
//			if (resultSet != null) {
//				while (resultSet.next()) {
//					//String mobileNo, String referByMobileNo, int userId, int userLogicPool, int
//					int userId = 0;
//					int logicalPool = 0;
//					String mobileNo = null;
//					try {
//						userId = resultSet.getInt("UserId");
//						logicalPool = resultSet.getInt("LogicalPool");
//						mobileNo = resultSet.getString("MobileNo");
//						DataValidateUserMobileInfo info = new DataValidateUserMobileInfo(
//								userId,
//								logicalPool,
//								mobileNo
//						);
//						result.put(info.getUserId(), info);
//					} catch (Exception ee) {
//						LOGGER.info(String.format(" new UserMobileInfo error, uid=%s,LogicalPool=%s, MobileNo=%s", userId,
//								logicalPool,
//								mobileNo));
//					}
//
//
//				}
//			}
//		} catch (Exception e) {
//			LOGGER.error("uids=%s" + new Gson().toJson(userIds), e);
//
//		} finally {
//			if (statement != null) statement.close();
//			if (connection != null) connection.close();
//		}
//		return result;
//	}

//	public List<Integer> getUserGroupsNoMobile() throws SQLException {
//		String sql = "select distinct UserId from GRP_UserGroups where MobileNo is null limit 1000";
//		Connection connection = null;
//		PreparedStatement statement = null;
//		List<Integer> result = new ArrayList<Integer>();
//		try {
//			connection = grpdb.getConnection();
//			statement = connection.prepareStatement(sql);
//			ResultSet resultSet = statement.executeQuery();
//
//			if (resultSet != null) {
//				while (resultSet.next()) {
//					//String mobileNo, String referByMobileNo, int userId, int userLogicPool, int groupId
//					result.add(resultSet.getInt("UserId"));
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (statement != null) statement.close();
//			if (connection != null) connection.close();
//		}
//		return result;
//
//	}

	public int upUserGroups(DataValidateGroupMemberInfo memberInfo) throws Exception {
		String sql = "update GRP_UserGroups set MobileNo=?  where UserId =?  ";
		int ret = 0;
		try {
			ret = getGrpDatabase(memberInfo.getUserLogicPool()).executeNonQuery(sql, memberInfo.getMobileNo().toString(), memberInfo.getUserId());
		} catch (Exception e) {
			LOGGER.error("DataValidateGroupMemberInfo=" + new Gson().toJson(memberInfo), e);
		}
		return ret;
	}

	@Override
	public List<GroupIndex> getUserGroupList(int userid, int logicPool) throws Exception {
		String sql = "select Identity,GroupId,GroupLogicalPool,UserId from GRP_UserGroups where userid = ?";
		DataTable dt = getGrpDatabase(logicPool).executeTable(sql, userid);
		List<GroupIndex> groupList = new ArrayList<GroupIndex>();
		for (DataRow dr : dt.getRows()) {
			if (dr.getInt("Identity") == 61) {
				continue;
			}
			GroupIndex index = new GroupIndex();
			index.setGroupId(dr.getInt("GroupId"));
			index.setLogicalPool(dr.getInt("GroupLogicalPool"));
			groupList.add(index);
		}
		return groupList;
	}
}